package com.peng.ivos.audit.service.impl;

import com.peng.ivos.application.mapper.ApplicationMapper;
import com.peng.ivos.application.pojo.dto.ApplicationQuery;
import com.peng.ivos.application.pojo.entity.Application;
import com.peng.ivos.application.pojo.vo.ApplicationVO;
import com.peng.ivos.audit.mapper.AuditMapper;
import com.peng.ivos.audit.pojo.dto.AuditQuery;
import com.peng.ivos.audit.pojo.dto.AuditSaveParam;
import com.peng.ivos.audit.pojo.entity.Audit;
import com.peng.ivos.audit.pojo.vo.AuditVO;
import com.peng.ivos.audit.service.AuditService;
import com.peng.ivos.base.enums.ApplicationStatusEnum;
import com.peng.ivos.base.enums.AuditStatusEnum;
import com.peng.ivos.base.response.JsonResult;
import com.peng.ivos.user.mapper.UserMapper;
import com.peng.ivos.user.pojo.dto.UserQuery;
import com.peng.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 审批表业务实现类
 *
 * @author： Peng
 * @date： 2024/5/24
 * @version: 1.0
 */
@Service
@Slf4j
public class AuditServiceImpl implements AuditService {
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationMapper applicationMapper;


    @Override
    public JsonResult selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单参数:auditQuery={}", auditQuery);
        //selectAudit这里要audit与application关联查询大部分数据,但审批人数据需要加工
        List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
        log.debug("查询审批单列表:auditVOList={}", auditVOList);
        //循环取出每一个查询到的审批单对象
        for (int i = 0; i < auditVOList.size(); i++) {
            AuditVO auditVO = auditVOList.get(i);
            //准备审批人数据
            assignAuditUserList(auditVO);
        }
        return JsonResult.success("查询审批单成功", auditVOList);
    }

    @Override
    public JsonResult updateAudit(AuditSaveParam auditSaveParam) {
        //将前端传入的数据赋值给audit
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam, audit);
        log.debug("修改审批单参数:audit={}", audit);
        //准备当前审批单对应的申请单的更新数据
        Application application = new Application();
        application.setId(audit.getApplicationId());
        //更新审批单状态为已审核-30
        if (Objects.equals(audit.getAuditStatus(), AuditStatusEnum.AUDITED.getCode())) {
            auditMapper.update(audit);
            //查询该申请单ID下的其他未审批的审批单数量，0-已全审核完 1-还有一人未审核
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if (count > 0) {
                //还有人未审核，申请单状态初始状态为已发起——修改为审核中
                //修改未审批人的审批单状态，先查询下一条审批单，下条审批单的sort就是当前审批单的sort+1,其他数据不变
                auditQuery.setAuditSort(audit.getAuditSort() + 1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if (auditVOList != null && auditVOList.size() > 0){
                    AuditVO auditVO = auditVOList.get(0);
                    //准备下一个审批单的更新数据
                    audit.setId(auditVO.getId());
                    audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit);
                }
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
                return JsonResult.success("审批通过，申请单状态修改为审核中");
            } else {
                //已全审核完，申请单状态修改为已结束——修改为已结束
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
                return JsonResult.success("已全部审核完成，申请单状态修改为已审核");
            }
        } else if (Objects.equals(audit.getAuditStatus(), AuditStatusEnum.REJECTED.getCode())){
            //审批状态为驳回审批不通过，申请单状态修改为已结束——修改为已结束
            //更新审批单状态为已驳回——修改自己审批单的状态
            auditMapper.update(audit);
            //根据申请单ID查询所有审批单数据——修改另一个人的审批单的数据
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if (auditVOList != null && auditVOList.size() > 0){
                for (int i = 0; i < auditVOList.size(); i++) {
                    AuditVO auditVO = auditVOList.get(i);
                    //此时另一个人审批单的状态为待他人审批，锁定后直接删除该条审批单数据即可
                    if (AuditStatusEnum.PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            //修改申请单状态为已结束，添加拒绝原因
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
            return JsonResult.success("审批已被驳回，申请单状态修改为已结束");
        }
        return JsonResult.error("审批状态异常，无法进行审批");
    }

    //查对应审批单的审批人数据
    //auditUserIdList=[3,1] auditUsernameList=lily,tom(String)
    private void assignAuditUserList(AuditVO auditVO) {
        List<String> usernameList = new ArrayList<>();
        List<Long> userIdList = new ArrayList<>();
        //需查询当前登录用户审批的当前申请单下的所有审批人
        AuditQuery auditQuery = new AuditQuery();
        auditQuery.setApplicationId(auditVO.getApplicationId());
        List<AuditVO> auditVOList = auditMapper.selectAuditByExample(auditQuery);
        //依次遍历每个审批人,获取审批人的id与username,分别装入上方的两个list中
        UserQuery userQuery = new UserQuery();
        for (int i = 0; i < auditVOList.size(); i++) {
            Long userId = auditVOList.get(i).getAuditUserId();
            userIdList.add(userId);
            userQuery.setId(userId);
            UserVO user = userMapper.selectUserByExample(userQuery).get(0);
            usernameList.add(user.getUsername());
        }
        //姓名是String类型,需要使用逗号分隔
//        StringJoiner stringJoiner = new StringJoiner(",");
//        for(String username : usernameList){
//            stringJoiner.add(username);
//        }
        String usernameArr = usernameList.stream().collect(Collectors.joining(","));
        //把准备好的审核人id与审核人姓名list数据存入auditVO中
        auditVO.setAuditUserIdList(userIdList);
        auditVO.setAuditUsernameList(usernameArr);
    }
}
